<template>
  <div>
    <!--  分隔行   -->
    <el-row>
      <el-col :span="24">
        <div class="grid-content bg-purple-light">
          <div style="float: left; margin: 20px 100px; font-weight: 700;color:#606266;font-size: 20px">
            <i class="el-icon-search"></i>司机查询
          </div>
        </div>
      </el-col>
    </el-row>
    <!--  查询条件   -->
    <el-form :inline="true" :model="queryForm" style="text-align: left; margin: 0 10%">
      <el-form-item label="司机身份证号">
        <el-input v-model="queryForm.driverId" placeholder="司机身份证号" clearable></el-input>
      </el-form-item>
      <el-form-item label="司机姓名">
        <el-input v-model="queryForm.driverName" placeholder="司机姓名" clearable></el-input>
      </el-form-item>
      <el-form-item label="联系电话">
        <el-input v-model="queryForm.driverTel" placeholder="联系电话" clearable></el-input>
      </el-form-item>
      <!--    查询按钮-->
      <el-form-item>
        <el-button type="info" @click="getList" plain>查询</el-button>
        <el-button type="info" @click="add()" plain>新增</el-button>
        <el-button type="info" @click="resetForm()" plain>重置</el-button>
      </el-form-item>
    </el-form>
    <!--  分隔行   -->
    <el-row>
      <el-col :span="24">
        <div class="grid-content bg-purple-light">
          <div style="float: left; margin: 0 100px; font-weight: 700;color:#606266;font-size: 20px">
            <i class="el-icon-s-unfold"></i>数据列表
          </div>
        </div>
      </el-col>
    </el-row>
    <!--  数据表格 样式块-->
    <div id="s" class="animate__animated animate__zoomIn animate__delay-0.5s" style="margin-top: 20px">
      <!--  数据表格   -->
      <el-table :data="tableData" style="width: 100%;" :border="true"
                :header-cell-style="{background:'#209e91', color:'#ffffff',textAlign:'center'}">
        <el-table-column
          type="index"
          label="序号"
          :index="indexAdd"
          width="50"
          align="center">
        </el-table-column>
        <el-table-column
          prop="driverCompany"
          label="所属公司"
          sortable
          align="center"
          width="200">
        </el-table-column>
        <el-table-column
          prop="driverName"
          label="司机姓名"
          sortable
          align="center"
          width="120">
        </el-table-column>
        <el-table-column
          prop="driverId"
          label="身份证号"
          sortable
          align="center"
          width="200">
        </el-table-column>
        <el-table-column
          prop="driverTel"
          label="联系电话"
          sortable
          align="center">
        </el-table-column>
        <el-table-column
          prop="sex"
          label="性别"
          sortable
          align="center"
          width="100">
        </el-table-column>
        <el-table-column
          prop="status"
          label="状态"
          width="100"
          align="center">
          <template v-slot="scope">
            <el-switch
              v-model="scope.row.status"
              :active-value="'1'"
              :inactive-value="'0'"
              active-color="#72d572"
              inactive-color="#91a7ff">
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column
          prop="contact"
          label="紧急联系人"
          sortable
          align="center">
        </el-table-column>
        <el-table-column
          prop="contactTel"
          label="紧急联系人电话"
          sortable
          align="center">
        </el-table-column>
        <el-table-column
          prop="createTime"
          align="center"
          label="新增时间">
        </el-table-column>
        <el-table-column
          prop="modifyTime"
          align="center"
          label="修改时间">
        </el-table-column>
        <el-table-column
          label="操作"
          align="center"
          width="100">
          <template v-slot="scope">
            <el-button @click="edit(scope.row)" type="text" size="small"  >编辑</el-button>
            <el-popconfirm title="确定删除吗？" @confirm="remove(scope.row)">
              <el-button v-if="scope.row.checked!='是'" slot="reference" type="text" size="small"  >删除</el-button>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <!--  分割行   -->
      <el-row>
        <el-col :span="24">
          <div class="grid-content bg-purple-light">
            <div style="margin: 20px"></div>
          </div>
        </el-col>
      </el-row>
      <!--  分页   -->
      <el-pagination
        @size-change="getList"
        @current-change="getList"
        :current-page.sync="queryForm.pageNum"
        :page-sizes="[10, 20, 30, 40, 60, 80, 100]"
        :page-size.sync="queryForm.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
      <!--  分割行  -->
      <el-row>
        <el-col :span="24">
          <div class="grid-content bg-purple-light">
            <div style="margin: 20px"></div>
          </div>
        </el-col>
      </el-row>
    </div>
    <!--  新增/修改页面   -->
    <el-dialog :title="title" :visible.sync="show" width="30%">
      <span>
        <el-form :model="form" :rules="rules" ref="ruleForm" label-width="150px">
          <el-form-item label="所属承运商" prop="driverCompany">
             <el-input v-model="form.driverCompany"></el-input>
          </el-form-item>
          <el-form-item label="司机姓名" prop="driverName">
             <el-input v-model="form.driverName"></el-input>
          </el-form-item>
          <el-form-item label="身份证号" prop="driverId">
             <el-input v-model="form.driverId"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
             <el-input v-model="form.password" show-password></el-input>
          </el-form-item>
          <el-form-item label="重复" prop="checkPassword">
             <el-input v-model="form.checkPassword" show-password></el-input>
          </el-form-item>
          <el-form-item label="性别" prop="sex">
             <el-select v-model="form.sex" placeholder="请选择" style="width: 100%">
                <el-option
                  v-for="item in sexList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
             </el-select>
          </el-form-item>
          <el-form-item label="状态" prop="status">
             <el-select v-model="form.status" placeholder="请选择" style="width: 100%">
                <el-option
                  v-for="item in statusList" style="{'color':form.status==1? '#72d572':'#91a7ff'}"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
             </el-select>
          </el-form-item>
          <el-form-item label="联系电话" prop="driverTel">
             <el-input v-model="form.driverTel"></el-input>
          </el-form-item>
          <el-form-item label="紧急联系人" prop="contact">
             <el-input v-model="form.contact"></el-input>
          </el-form-item>
          <el-form-item label="紧急联系人电话" prop="contactTel">
             <el-input v-model="form.contactTel"></el-input>
          </el-form-item>
          <!--    照片模块   -->
          <el-form-item label="身份证和驾照备证" prop="image" style="line-height: 16px!important;">
           <el-card shadow="always">
               <el-image v-for="ele in this.$store.state.baseDriverPhoto" :src="ele"
                         style="width: 150px; height: 150px"
                         :preview-src-list="$store.state.baseDriverPhoto"
                         :fit="'cover'"></el-image>
                <el-upload
                  class="upload-demo"
                  ref="upload"
                  :action="action"
                  list-type="picture-card"
                  :limit="3"
                  :class="{hide:hideUpload}"
                  :on-change="handleChange"
                  :on-preview="handlePictureCardPreview"
                  :before-upload="beforeAvatarUpload"
                  :on-remove="handleRemove"
                  :file-list="fileList"
                  :auto-upload="false">
                  <i class="el-icon-plus"></i>
                </el-upload>
             <!--    照片墙放大后，不变成灰色append-to-body  -->
                <el-dialog :visible.sync="dialogVisible" :append-to-body="true" width="70%">
                  <img width="100%" :src="dialogImageUrl" alt="">
                </el-dialog>
             <div class="el-upload__tip" style="margin-top: 0;color: #606266;font-weight: 600;font-size: 15px">只能上传3张图片，文件格式要求为jpeg文件，且不超过2MB</div>
            </el-card>
          </el-form-item>
        </el-form>
      </span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="show = false">取 消</el-button>
        <el-button type="primary" @click="submit()">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "Driver",
  data() {
    //密码校验
    let checkPassword = (rule, value, callback) => {
      if ((value === '' || undefined === value) && this.form.password != '') {
        callback(new Error('请再次输入密码'));
      } else if (value !== this.form.password && this.form.password != '') {
        callback(new Error('两次输入密码不一致!'));
      } else {
        callback();
      }
    };
    return {
      //经过base64进行图片转换
      finalPhotoToShow:[],
      //后台返回图片数据
      photoToShow: [],
      //弹出图片地址
      dialogImageUrl: '',
      //弹出框是否可见
      dialogVisible: false,
      //上传照片路径
      action: 'api/baseDriver/uploadImg',
      //照片文件列表
      fileList: [],
      //隐藏上传图标
      hideUpload: false,
      //照片限制张树
      limitCount: 3,
      //查询对象
      queryForm: {
        //司机身份证号
        driverId: '',
        //司机姓名
        driverName: '',
        //司机联系方式
        driverTel: '',
        //起始页面
        pageNum: 1,
        //起始页面条数
        pageSize: 10
      },
      //表格数组
      tableData: [],
      //共多少条
      total: 0,
      //显示新增、修改
      show: false,
      //表单对象
      form: {},
      //标题
      title: '',
      //性别列表
      sexList: [
        {
          value: '男'
        },
        {
          value: '女'
        }
      ],
      //状态列表
      statusList: [
        {
          value: '1',
          label: '已配车'
        },
        {
          value: '0',
          label: '未配车'
        }
      ],
      //校验对象
      rules: {
        //所属公司，必填
        driverCompany: [{required: true, message: '请输入所属公司', trigger: 'blur'}],
        //司机姓名，必填
        driverName: [{required: true, message: '请输入司机姓名', trigger: 'blur'}],
        //密码，必填
        password: [{required: true, message: '请输入密码', trigger: 'blur'}],
        //校验密码，必填
        checkPassword: [{required: true, validator: checkPassword, trigger: 'blur'}],
        //性别，必填
        sex: [{required: true, message: '请输入性别', trigger: 'change'}],
        //状态，必填
        status: [{required: true, message: '请选择状态', trigger: 'change'}],
        //紧急联系人联系方式，非必填
        contactTel: [
          {
            message: '联系电话未填写或格式不正确',
            pattern: /^1((34[0-8])|(8\d{2})|(([35][0-35-9]|4[579]|66|7[35678]|9[1389])\d))\d{7}$/,
          }
        ],
        //司机联系方式，必填，唯一
        driverTel: [
          {
            required: true,
            pattern: /^1((34[0-8])|(8\d{2})|(([35][0-35-9]|4[579]|66|7[35678]|9[1389])\d))\d{7}$/,
            message: '联系电话未填写或格式不正确',
            trigger: 'blur'
          }
        ],
        //司机身份证号，必填，唯一
        driverId: [
          {
            required: true,
            pattern: /^(([1-9][0-9]{5}(19|20)[0-9]{2}((0[1-9])|(1[0-2]))([0-2][1-9]|10|20|30|31)[0-9]{3}([0-9]|X|x))|([1-9][0-9]{5}[0-9]{2}((0[1-9])|(1[0-2]))([0-2][1-9]|10|20|30|31)[0-9]{3}))$/,
            message: "身份证未填写或格式不正确",
            trigger: "blur"
          }
        ],
      }
    }
  },
  methods: {
    //表格序号
    indexAdd(index) {
      const page = this.queryForm.pageNum // 当前页码
      const pageSize = this.queryForm.pageSize // 每页条数
      return index + 1 + (page - 1) * pageSize
    },
    //查询内容重置
    resetForm() {
      this.queryForm.driverId = ''
      this.queryForm.driverName = ''
      this.queryForm.driverTel = ''
    },
    //查询所有司机信息
    getList() {
      this.$axios({
        url: 'baseDriver/list',
        method: 'post',
        data: this.queryForm
      }).then(res => {
        if (res.data.success) {
          this.tableData = res.data.object.list;
          this.total = res.data.object.total;
        }
      }).catch(err => {
        this.$message.error(err.message);
      })
    },
    //新增司机信息
    add() {
      this.$store.commit("baseDriverPhoto",[])
      //设置标题
      this.title = '新增'
      //显示对话框
      this.show = true
      //清空表单
      this.form = {}
      //清空校验结果
      this.$nextTick(() => {
        this.$refs['ruleForm'].clearValidate();
      })
      this.rules.password[0].required = true;
      this.rules.checkPassword[0].required = true;
    },
      // 编辑司机信息
    showDriverPhotos(row) {
      //发送新的请求，传driverId
      this.$axios({
        url: 'baseDriverPhoto/plist',
        method: 'post',
        data: {driverId: row.driverId}
      }).then(res => {
        if (res.data.success) {
           const finalPhotoToShow=[]
          this.photoToShow = res.data.object;
          // 如果照片不是空   照片进行回显
          if ( this.photoToShow != undefined) {
            for (const ele of  this.photoToShow) {
              finalPhotoToShow.push('data:image/jpeg;base64,' + ele)
            }
            this.$store.commit("baseDriverPhoto",finalPhotoToShow)
          }
        }
      }).catch(err => {
        this.$message.error(err.message);
      })
    },
    edit(row) {
      this.$store.commit("baseDriverPhoto",[])
      this.showDriverPhotos(row)
      this.title = '修改'
      //清空表单
      this.form = {}
      //给form对象赋值
      this.form = Object.assign({}, row);
      //显示对话框
      this.form.password = ''
      this.show = true
      //清空校验结果
      this.$nextTick(() => {
        this.$refs['ruleForm'].clearValidate();
      })
      this.disabled = true
      this.rules.password[0].required = false;
      this.rules.checkPassword[0].required = false;
    },
    //删除司机
    remove(row) {
      this.$axios({
        url: 'baseDriver/remove/' + row.id,
        method: 'post'
      }).then(res => {
        if (res.data.success) {
          this.$message({
            message: res.data.message,
            type: 'success'
          });
          this.getList();
        } else {
          this.$message.error(res.data.message);
        }
      }).catch(err => {
        this.$message.error(err.message);
      })
    },
    //提交新增、编辑信息
    submit() {
      this.$refs['ruleForm'].validate((valid) => {
        if (valid) {
          //校验通过
          if (this.title == '新增') {
            this.$refs['ruleForm'].validate((valid) => {
              if (valid) {
                this.$axios({
                  url: 'baseDriver/add',
                  method: 'post',
                  data: this.form
                }).then(res => {
                  if (res.data.success) {
                    this.$store.commit("baseDriverPhoto",[])
                    this.show = false;
                    //上传图片
                    this.submitUpload();
                    this.getList();
                    this.$message.success('上传成功');
                  } else {
                    this.$message.error(res.data.message);
                  }
                }).catch(err => {
                  this.$message.error(err.message);
                })
              }
            });
          } else {
            this.$axios({
              url: 'baseDriver/edit',
              method: 'post',
              data: this.form
            }).then(res => {
              if (res.data.success) {
                this.$store.commit("baseDriverPhoto",[])
                this.show = false;
                //上传图片
                this.submitUpload();
                this.getList();
                this.$message.success('修改成功');
              } else {
                this.$message.error(res.data.message);
              }
            }).catch(err => {
              this.$message.error(err.message);
            })
          }
        }
      });
    },
    // 参数为上传的文件和文件列表，若返回 false 或者返回 Promise 且被 reject，则停止删除
    handleChange(file, fileList) {
      this.fileList = fileList;
      this.hideUpload = fileList.length >= this.limitCount;
    }, // 参数为上传的文件和文件列表，若返回 false 或者返回 Promise 且被 reject，则停止删除
    handleRemove(file, fileList) {
      this.fileList = fileList;
      this.hideUpload = fileList.length >= this.limitCount;
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg';
      const isLt = file.size / 1024 / 1024 < 2;
      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!');
      }
      if (!isLt) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }
      return isJPG && isLt;
    },
    submitUpload() {
      this.loading = true;
      // 判断是否有文件再上传
      if (this.fileList.length === 0) {
        this.loading = false;
        return this.$message.warning('请选取文件后再上传')
      }
      // 创建一个空的FormData对象:
      const formData = new FormData()
      // 可以使用FormData.append来添加键/值对到表单里面；
      this.fileList.forEach((file) => {
        formData.append('file', file.raw)
      })
      // 添加其他的自定义参数到后端
      formData.append('driver', this.form.driverId)
      this.$axios({
        url: 'baseDriverPhoto/uploadImg',
        method: 'post',
        data: formData
      }).then(res => {
        if (res.data.success) {
          if (res.data.code == 200) {
            this.$store.commit('baseDriverPhoto', res.data.object)
          } else {
            this.$message.error('上传图片失败');
          }
          this.$refs.upload.clearFiles();
          this.loading = false;
          this.show = false;
          //清空fileList
          this.fileList = [];
        }
      }).catch(err => {
        this.$refs.upload.clearFiles();
        this.loading = false;
        this.show = false;
        this.fileList = [];
        this.$message.error(err.message);
      })
    },

  },
  created() {
    this.getList()
  },
  computed: {
  },
}
</script>
<!--   当上传备证数量达到3张后，不显示上传图标（需全局样式）-->
<style>
/*  照片数量达到3张不显示上传图标*/
.hide .el-upload--picture-card {
  display: none
}
</style>
<style scoped>
/*  按钮移上样式*/
.el-button--info:hover {
  background: #209e91;
  border-color: #209e91;
  color: #FFF;
}
/* 整体模块样式*/
#s {
  width: 90%;
  margin: 10px auto;
  background-color: #ffffff;
  box-shadow: 10px 10px 5px #c4c6c7;
  border-radius: 5px
}

.el-table-column {
  text-align: center;
}
</style>
